<?php
if (!defined('ABSPATH')) { exit; }

global $wpdb;
$visits = $wpdb->prefix . 'spider_visits';

$type = sanitize_text_field($_GET['type'] ?? '');
$status = sanitize_text_field($_GET['status'] ?? '');
$keyword = sanitize_text_field($_GET['q'] ?? '');

// 分页参数
$allowed_pp = array(10,20,30);
$per_page = intval($_GET['pp'] ?? 10);
if (!in_array($per_page, $allowed_pp, true)) { $per_page = 10; }
$page_no = max(1, intval($_GET['pg'] ?? 1));
$offset = ($page_no - 1) * $per_page;

$where = '1=1';
$params = array();
if ($type !== '') { $where .= ' AND spider_name LIKE %s'; $params[] = '%' . $wpdb->esc_like($type) . '%'; }
if ($status !== '') { $where .= ' AND response_code = %d'; $params[] = intval($status); }
if ($keyword !== '') { $where .= ' AND url LIKE %s'; $params[] = '%' . $wpdb->esc_like($keyword) . '%'; }

// 统计总数
$count_sql = $params ? $wpdb->prepare("SELECT COUNT(*) FROM $visits WHERE $where", $params) : "SELECT COUNT(*) FROM $visits WHERE $where";
$total_items = intval($wpdb->get_var($count_sql));
$total_pages = max(1, ceil($total_items / $per_page));
if ($page_no > $total_pages) { $page_no = $total_pages; $offset = ($page_no - 1) * $per_page; }

// 读取页数据
if ($params) {
    $params_with_limit = array_merge($params, array($per_page, $offset));
    $query = $wpdb->prepare("SELECT * FROM $visits WHERE $where ORDER BY visit_time DESC LIMIT %d OFFSET %d", $params_with_limit);
} else {
    $query = $wpdb->prepare("SELECT * FROM $visits WHERE $where ORDER BY visit_time DESC LIMIT %d OFFSET %d", $per_page, $offset);
}
$rows = $wpdb->get_results($query, ARRAY_A);

?>
<div class="wrap">
    <h1>记录管理</h1>
    <?php if (!function_exists('wp_spider_is_premium') || !wp_spider_is_premium()): ?>
        <div class="notice notice-warning"><p>“拦截”等高级操作需要PRO激活。</p></div>
    <?php endif; ?>
    <div class="toolbar">
        <form method="get" action="" class="filters">
            <input type="hidden" name="page" value="wp-spider-monitor-records" />
            <select name="type">
                <option value="">所有类型</option>
                <option value="Google">Google</option>
                <option value="Baidu">Baidu</option>
                <option value="Bing">Bing</option>
            </select>
            <select name="status">
                <option value="">所有状态</option>
                <option value="200">200</option>
                <option value="301">301</option>
                <option value="404">404</option>
                <option value="500">500</option>
            </select>
            <input type="text" name="q" value="<?php echo esc_attr($keyword); ?>" placeholder="输入蜘蛛名称" />
            <select name="pp">
                <?php foreach ([10,20,30] as $pp): ?>
                    <option value="<?php echo $pp; ?>" <?php selected($per_page, $pp); ?>>每页 <?php echo $pp; ?></option>
                <?php endforeach; ?>
            </select>
            <button class="button">筛选</button>
        </form>
    </div>
    <table class="wp-list-table widefat fixed striped">
        <thead>
            <tr>
                <th>时间</th>
                <th>蜘蛛</th>
                <th>URL</th>
                <th>近7天占比</th>
                <th>状态</th>
                <th style="width:160px;">操作</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($rows)): ?>
                <tr><td colspan="6">暂无数据</td></tr>
            <?php else: foreach ($rows as $r): ?>
                <tr>
                    <td><?php echo esc_html($r['spider_name']); ?></td>
                    <td>—</td>
                    <td>
                        <span class="status-pill status-<?php echo intval($r['response_code']); ?>">
                            <?php echo intval($r['response_code']); ?>
                        </span>
                    </td>
                    <td>
                        <div class="actions">
                            <button class="button set-rule" data-spider="<?php echo esc_attr($r['spider_name']); ?>" data-rule="ignored">忽略</button>
                            <button class="button set-rule-premium" data-spider="<?php echo esc_attr($r['spider_name']); ?>" data-rule="blocked" <?php echo (function_exists('wp_spider_is_premium') && wp_spider_is_premium()) ? '' : 'disabled'; ?>>拦截</button>
                        </div>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
        </tbody>
    </table>
    <?php
    // 分页导航
    $base_url = remove_query_arg(array('pg'), $_SERVER['REQUEST_URI']);
    if (strpos($base_url, '?') === false) { $base_url .= '?'; } else { $base_url .= '&'; }
    ?>
    <div class="tablenav bottom">
        <div class="tablenav-pages">
            <span class="displaying-num">共 <?php echo number_format_i18n($total_items); ?> 条 · 第 <?php echo $page_no; ?>/<?php echo $total_pages; ?> 页</span>
            <?php if ($total_pages > 1): ?>
                <a class="button" href="<?php echo esc_url($base_url . 'pg=1&pp=' . $per_page); ?>">«</a>
                <a class="button" href="<?php echo esc_url($base_url . 'pg=' . max(1, $page_no-1) . '&pp=' . $per_page); ?>">‹</a>
                <a class="button" href="<?php echo esc_url($base_url . 'pg=' . min($total_pages, $page_no+1) . '&pp=' . $per_page); ?>">›</a>
                <a class="button" href="<?php echo esc_url($base_url . 'pg=' . $total_pages . '&pp=' . $per_page); ?>">»</a>
            <?php endif; ?>
        </div>
    </div>

    <div class="notice notice-info" style="margin-top:15px;">
        <p><strong>PRO版功能：</strong> 高级筛选（时间范围、蜘蛛类型、路径正则等）、批量导出CSV/JSON、拦截与忽略规则、智能标注、占比趋势、白/黑名单管理等。请前往“PRO版本”页面了解并激活。</p>
    </div>
</div>

<style>
.toolbar { margin:12px 0; }
.filters select, .filters input { margin-right:8px; }
.status-pill { display:inline-block; padding:2px 8px; border-radius:12px; color:#fff; font-size:12px; }
.status-200 { background:#46b450; }
.status-301 { background:#ffb900; }
.status-404 { background:#dc3232; }
.status-500 { background:#d63638; }
.actions .button { margin-right:6px; }
</style>

<script>
(function($){
    function isPremium(){ return (window.wpSpiderMonitor && wpSpiderMonitor.subscription && wpSpiderMonitor.subscription.is_premium); }
    $('.set-rule').on('click', function(e){
        e.preventDefault();
        var btn = $(this);
        $.post(ajaxurl, {
            action: 'spider_set_rule',
            spider: btn.data('spider'),
            rule: btn.data('rule'),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(resp){
            if (resp && resp.success){
                alert('已设置为：' + resp.data.rule);
            } else {
                alert('设置失败');
            }
        });
    });

    $('.set-rule-premium').on('click', function(e){
        e.preventDefault();
        if (!isPremium()) { alert('拦截为高级功能，请在PRO版本页面激活。'); return; }
        var btn = $(this);
        $.post(ajaxurl, {
            action: 'spider_set_rule',
            spider: btn.data('spider'),
            rule: btn.data('rule'),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(resp){
            if (resp && resp.success){ alert('已设置为：' + resp.data.rule); } else { alert('设置失败'); }
        });
    });
})(jQuery);
</script>


